package com.zhiche.lisa.lspm.controller;

import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.zhiche.lisa.core.enums.CommonEnum;
import com.zhiche.lisa.core.supports.RestfulResponse;
import com.zhiche.lisa.lspm.dao.model.weiXin.WeiXinExport;
import com.zhiche.lisa.lspm.service.utils.common.Cache;
import com.zhiche.lisa.lspm.service.utils.common.MD5Util;
import com.zhiche.lisa.lspm.service.utils.common.excel.ExcelCommon;
import com.zhiche.lisa.lspm.service.utils.common.excel.ExcelUtil;
import com.zhiche.lisa.lspm.service.weiXin.WeiXinExportService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * excel 相关接口
 * </p>
 *
 * @author liuanshun
 * @since 2018-08-29
 */
@RestController
@RequestMapping("/excel")
@Api(value = "/excel", description = "EXCEL导出", tags = {"导出接口"})
public class ExcelController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExcelController.class);

    /**
     * excel资源缓冲区
     */
    private final static Cache<HSSFWorkbook> RESOURCES = new Cache<HSSFWorkbook>();

    /**
     * 统一配置字段映射结果
     */
    @Autowired
    private WeiXinExportService weiXinExportService;

    /**
     * 下载资源
     *
     * @param key      资源key
     * @param response 自动注入结果对象
     * @return 下载资源流
     * @throws IOException
     */
    @ApiOperation(value = "微信公众号报表导出", notes = "微信公众号报表导出", httpMethod = "GET")
    @GetMapping("/exportResource")
    public RestfulResponse<String> exportResouce(@RequestParam String key, HttpServletResponse response) throws IOException {
        if (Strings.isNullOrEmpty(key)) return new RestfulResponse<>(CommonEnum.ERROR.getCode(), "文件key接收异常", null);
        RestfulResponse<String> restful = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        //获取缓冲区数据资源
        HSSFWorkbook excel = RESOURCES.get(key);
        if (Objects.isNull(excel)) {
            //未获取到资源抛出提示
            restful = new RestfulResponse<>(CommonEnum.ERROR.getCode(), "资源文件不存在", null);
        } else {
            RESOURCES.remove(key);
            LOGGER.info("DownloaExlFile:" + key);
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + "resource.xls");
            OutputStream ouputStream = response.getOutputStream();
            excel.write(ouputStream);
            ouputStream.flush();
            ouputStream.close();
        }
        return restful;
    }



    /***
     * 获取excel微信公众号报表数据
     * @return 返回文件名称及excel文件的URL
     * @throws IOException
     */
    @ApiOperation(value = "微信公众号报表导出", notes = "微信公众号报表导出", httpMethod = "POST")
    @PostMapping("/exportWeiXinUsageRate")
    public RestfulResponse<String> exportWeiXinUsageRate(@RequestBody Map<String, Object> condition) {
        /**
         * 配置映射表头
         */
        //微信公众号使用率
        Map<String, Object> weiXinUsageRateMapping = Maps.newLinkedHashMap();
        /**
         * 设置导出映射字段
         */
        {
            weiXinUsageRateMapping.put("id", "序号");
            weiXinUsageRateMapping.put("dtship", "调度时间");
            weiXinUsageRateMapping.put("origin", "起运地");
            weiXinUsageRateMapping.put("shipCount", "发运总数");
            weiXinUsageRateMapping.put("queueCount", "公众号报班数");
            weiXinUsageRateMapping.put("rate", "报班比例");
        }
        List<String> mapVal = ExcelCommon.getMapVal(weiXinUsageRateMapping);
        String[] titles = mapVal.toArray(new String[mapVal.size()]);
        List<WeiXinExport> list = weiXinExportService.queryWeChatPublicNumberUsageRate(condition);
        // 导出
        HSSFWorkbook excel = ExcelUtil.export("微信公众号报表导出", titles, list, weiXinUsageRateMapping);
        String key = MD5Util.backMD5(excel.toString());
        RESOURCES.put(key, excel);
        return new RestfulResponse<String>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), key);
    }
}